package com.cn.service;

import com.cn.entity.DeviceError;
import com.cn.entity.Material;
import com.cn.entity.RunStatusReport;
import com.cn.entity.TrigEventDetailCount;
import com.cn.utils.StringUtil;
import com.cn.utlis.IBase;
import com.cn.vo.RestStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

/**
 * Created by chenyuncong on 2019/3/27.
 */
@Service
public class RunStatusReportServiceImpl extends IBase<RunStatusReport> implements RunStatusReportService {

    final static Logger log = LoggerFactory.getLogger(RunStatusReportServiceImpl.class);

    @Autowired
    private DeviceErrorService deviceErrorService;
    @Autowired
    private TrigEventDetailCountService trigEventDetailCountService;
    @Autowired
    private MaterialService materialService;

    private Map<Integer, String> macMap = new HashMap<Integer, String>() {{
        put(1, "00:80:f4:40:3f:37");
        put(2, "00:80:f4:41:ae:35");
        put(3, "00:04:17:07:2f:5a");

        put(4, "00:80:f4:40:9e:9a");
        put(5, "00:80:f4:40:99:14");
        put(6, "00:04:17:07:5a:a4");

        put(7, "00:80:f4:40:b6:fe");
        put(8, "00:80:f4:40:99:1e");
        put(9, "00:80:f4:40:a0:61");

        put(10, "00:80:f4:40:9a:50");
        put(11, "00:80:f4:40:db:ff");

    }};

    public void getRunStatusTemplateList(String mac, String startTime, String endTime, int type) throws Exception {
        String typeMac = macMap.get(type);
        String strTimeSql = "select r.today,count(1) num from run_status_template_data r where r.mac=? GROUP BY r.today order by num desc limit 7";
        List<RestStatus> rsList = this.getList(strTimeSql, RestStatus.class, typeMac);

        String listSqlte = "select * from run_status_template_data where mac=? and today=?";
        String dErrorSql = "select * from device_error_template_data where mac=? and today=?";
        String eventSql = "select * from trig_event_detail_count_template_data where mac=? and today=?";
        String materialSql = "select * from material_template_data where mac=?";
        List<String> listStr = StringUtil.getDateList(startTime, endTime, null, "yyyy-MM-dd");
        List<Material> mList = null;

        for (int i = 0; i < rsList.size(); i++) {
            if (i < listStr.size()) {
                try {
                    RestStatus x = rsList.get(i);//获取分组数量最多的条数，有时间
                    String timeStr = x.getToday(); //
                    String nowTimeStr = listStr.get(i); //获取哪一个数据模板
                    int today = Integer.parseInt(nowTimeStr.replaceAll("-", "")); //某一天的时间
                    int checkCount = this.count("select count(1) from run_status_report where mac='" + mac + "' and today=" + today);
                    log.info("check当天数据为：" + checkCount + " 时间是：" + today + " 模板时间：" + nowTimeStr);
                    if (checkCount < 10) {

                        if(mList==null){
                            mList = this.getList(materialSql, Material.class, typeMac);
                            mList.forEach(o -> {
                                o.setId(null);
                                o.setMac(mac);
                                o.setToday(Integer.parseInt(listStr.get(0).replaceAll("-", "")));
                                o.getRegDate().setTime(toDate(o.getRegDate(), listStr.get(0)));
                            });
                            log.info("添加 Material 数据为：" + mList.size());
                            materialService.saveBatch(mList);
                        }

                        List<RunStatusReport> list = this.getList(listSqlte, RunStatusReport.class, typeMac, timeStr); //获取模板的数据
                        List<DeviceError> deList = this.getList(dErrorSql, DeviceError.class, typeMac, timeStr);
                        List<TrigEventDetailCount> eventList = this.getList(eventSql, TrigEventDetailCount.class, typeMac, timeStr);
                        list.forEach(o -> {
                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                            o.setId(null);
                            deList.forEach(de -> {
                                if (de.getUuid().equals(o.getUuid())) {
                                    de.setUuid(uuid);
                                }
                            });
                            o.setUuid(uuid);
                            o.setMac(mac);
                            o.getAddTime().setTime(toDate(o.getAddTime(), nowTimeStr));
                            o.getStartTime().setTime(toDate(o.getStartTime(), nowTimeStr));
                            o.getEndTime().setTime(toDate(o.getEndTime(), nowTimeStr));
                            o.setToday(today);
                        });
                        //事故集合
                        deList.forEach(o -> {
                            o.setToday(today);
                            o.setMac(mac);
                            o.setId(null);
                            o.getRegDate().setTime(toDate(o.getRegDate(), nowTimeStr));
                            o.getTheTime().setTime(toDate(o.getTheTime(), nowTimeStr));
                        });
                        //事件集合
                        eventList.forEach(o -> {
                            o.setId(null);
                            o.setMac(mac);
                            o.getRegDate().setTime(toDate(o.getRegDate(), nowTimeStr));
                            o.setUuid(UUID.randomUUID().toString().replaceAll("-",""));
                            o.setToday(today);
                            try {
                                o.setModDate(new Date(StringUtil.strToTime(nowTimeStr+" 18:00:00", "yyyy-MM-dd HH:mm:ss")));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                        });
                        trigEventDetailCountAndmaterial(mac,eventList);

                        log.info("添加deviceError数据为" + deList.size());
                        deviceErrorService.saveBatch(deList);
                        log.info("添加run_status数据为：" + list.size());
                        this.saveBatch(list);
                        log.info("添加trig_eventDetail_count数据为：" + eventList.size());
                        trigEventDetailCountService.saveBatch(eventList);
                    }


                    log.info("");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
    private void trigEventDetailCountAndmaterial(String mac,List<TrigEventDetailCount> eventList) throws Exception {
        String sql = "select * from material where mac=?";
        List<Material> list = this.getList(sql,Material.class,mac);
//        trigEventDetailCountService.updateBatch();
        eventList.forEach(x->{
            if(x.getEventName().equals("线1走线触发器")||x.getEventName().equals("线2走线触发器")){
                list.forEach(o->{
                    if(o.getName().equals("钢丝")){
                        x.setMaterialId(o.getId());
                    }
                });
            }else if(x.getEventName().equals("拉布触发器")){
                list.forEach(o->{
                    if(o.getName().equals("无纺布")){
                        x.setMaterialId(o.getId());
                    }
                });
            }
        });



    }

    private long toDate(Date date, String timeStr) {
        StringBuffer sb = new StringBuffer(timeStr);
        sb.append(" ").append(StringUtil.timeToStr(date.getTime()).split(" ")[1]);
        try {
            return StringUtil.strToTime(sb.toString(), "yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }
}
